package dominion.model.actions.base;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.List;

import dominion.model.Card;
import dominion.model.GameBoard;
import dominion.model.Player;
import dominion.model.actions.Action;
import dominion.utils.Constants;

public class ThroneRoom extends Action {

	public ThroneRoom() {
		cost = 4;
	}

	@Override
	public Card clone() {
		return new ThroneRoom();
	}

	@Override
	public String toString() {
		return "Throne Room";
	}

	@Override
	public String getDescription() {
		StringBuffer sb = new StringBuffer();
		sb.append(super.getDescription());
		sb.append("Choose an action card in your hand.\n");
		sb.append("Play it twice.\n");
		return sb.toString();
	}

	@Override
	public void doAction(Player player, GameBoard board, List<Player> players) throws IOException {
		int actions = 0;
		for (Card card : player.getHand().getList())
		{
			if (card instanceof Action)
			{
				actions++;
			}
		}
		if (actions < 2)
		{
			Constants.printer.print("No other actions to play with.");
			return;
		}
		player.changeAction(-1);
		playedCard(player);

		Constants.printer.print("Select an action card from hand: ");
		Constants.printer.print(player.printHand());
		String choice = null;
		BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
		while (true)
		{
			choice = in.readLine().trim().toLowerCase();
			Card target = Constants.cardMap.get(choice);
			if (!player.getHand().contains(choice))
			{
				Constants.printer.print("Card is not in hand.");
			}
			else if (!(target instanceof Action))
			{
				Constants.printer.print("Card must be an action card.");
			}
			else if (target instanceof ThroneRoom && actions < 4)
			{
				Constants.printer.print("Not enough action cards in hand.");
				player.changeAction(1);
				player.addToDeck(player.drawFromDeck(toString(), Constants.DISCARD_DECK), Constants.HAND);
				break;
			}
			else
			{
				player.changeAction(1);
				Card card = player.getHand().getCard(target.toString());
				card.doAction(player, board, players);
				Card again = player.drawFromDeck(target.toString(), Constants.DISCARD_DECK);
				player.addToDeck(again, Constants.HAND);
				player.changeAction(1);
				again.doAction(player, board, players);
				break;
			}
		}
	}
}
